<!DOCTYPE html>
<html lang="zh-CN">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0, maximum-scale=1.0, user-scalable=no">
    <title>车辆起点登记</title>
    <!-- 引入WeUI CSS -->
    <link rel="stylesheet" href="./weui/weui.min.css">
    <style>
        /* 全局样式 */
        body {
            
            /* background-image: url('./assets/1.png'); */
      background: linear-gradient(135deg, #348d5f 0%, #bfbf86 100%);
            font-family: -apple-system, BlinkMacSystemFont, "Segoe UI", Roboto, "Helvetica Neue", Arial, sans-serif;
            min-height: 100vh;
            padding-bottom: 20px;
                background-position:center;
        }
        
        .page-container {
            max-width: 600px;
            margin: 0 auto;
            padding: 15px;
        }
        
        /* 头部样式优化 */
        .header {
            text-align: center;
            margin-bottom: 25px;
            padding: 25px 0 15px;
            position: relative;
        }
        
        .header::after {
            content: '';
            position: absolute;
            bottom: 0;
            left: 50%;
            transform: translateX(-50%);
            width: 60px;
            height: 4px;
           background: linear-gradient(to right, #07C160, #ffffff);
            border-radius: 2px;
        }
        
        .header-title {
            font-size: 26px;
           color: white;
            font-weight: 600;
            margin-bottom: 10px;
            letter-spacing: 1px;
        }
        
        .header-desc {
            font-size: 15px;
           color: white;
            line-height: 1.5;
        }
          .weui-cells{
            background-color: transparent;
        }
        /* 表单样式优化 */
        .weui-form {
             background-color: rgba(255,255,255,0.97);
            border-radius: 16px;
            box-shadow: 0 8px 30px rgba(0, 0, 0, 0.08);
            overflow: hidden;
            transition: transform 0.3s ease;
        }
        
        .weui-form:hover {
            transform: translateY(-3px);
        }
        
        .weui-cells {
            margin-top: 0;
        }
        
        .weui-cell {
            padding: 18px 0;
            transition: background-color 0.2s;
        }
        
        .weui-cell:active {
            background-color: rgba(7, 193, 96, 0.05);
        }
        
        .weui-label {
            font-size: 17px;
            color: #333;
            width: 80px;
            font-weight: 500;
        }
        
        .weui-input {
            font-size: 16px;
            color: #333;
            padding: 10px 0;
            transition: border-color 0.3s;
            border-bottom: 1px solid #e5e5e5;
        }
        
        .weui-input:focus {
            border-bottom: 2px solid #07C160;
            padding-bottom: 9px;
        }
        
        .input-container {
            display: flex;
            align-items: center;
            width: 100%;
        }
        
        .weui-cell__bd {
            flex: 1;
        }
        
        /* 重量输入组样式 */
        .weight-group {
            display: flex;
            gap: 10px;
            margin-top: 10px;
            align-items: center;
        }
        
        .weight-group .weui-input {
            flex: 1;
        }
        
        /* 图片预览容器 */
        .preview-container {
            display: flex;
            flex-wrap: wrap;
            gap: 10px;
            margin-top: 10px;
        }
        
        .preview-item {
            width: calc(42.333% - 10px);
            border: 1px dashed #ccc;
            padding: 5px;
            border-radius: 4px;
            position: relative;
            background-color: #f9f9f9;
        }
        
        .preview-item img {
            width: 100%;
            height: 100px;
            object-fit: contain;
            cursor: pointer;
            transition: transform 0.3s;
        }
        
        .preview-item img:hover {
            transform: scale(1.02);
        }
        
        .preview-info {
            font-size: 12px;
            color: #666;
            overflow: hidden;
            text-overflow: ellipsis;
            white-space: nowrap;
            margin-top: 5px;
        }
        
        .preview-placeholder {
            color: #999;
            text-align: center;
            padding: 20px;
            border: 1px dashed #ddd;
            border-radius: 4px;
            width: 100%;
        }
        
        .remove-btn {
            position: absolute;
            top: 5px;
            right: 5px;
            background-color: rgba(255,0,0,0.7);
            color: white;
            border: none;
            border-radius: 50%;
            width: 20px;
            height: 20px;
            font-size: 12px;
            cursor: pointer;
            display: flex;
            align-items: center;
            justify-content: center;
            z-index: 1;
        }
        
        /* 上传状态指示器 */
        .upload-status {
            position: absolute;
            top: 50%;
            left: 50%;
            transform: translate(-50%, -50%);
            background: rgba(0,0,0,0.7);
            color: white;
            padding: 5px 10px;
            border-radius: 4px;
            font-size: 12px;
        }
        
        /* 错误提示样式 */
        .weui-cells__tips {
            font-size: 14px;
            color: #f43530!important;
            margin-top: 6px;
            padding-left: 80px;
            display: none;
            animation: fadeIn 0.3s;
        }
        
        /* 提交按钮区域 */
        .weui-form__opr-area {
            margin: 35px 0 25px;
        }
        
        .weui-btn_primary {
            background: linear-gradient(312deg, #47cb87 0%, #bfbf86);
            border-radius: 10px;
            height: 50px;
            font-size: 18px;
            font-weight: 500;
            box-shadow: 0 4px 10px rgba(7, 193, 96, 0.3);
            transition: all 0.3s;
        }
        
        .weui-btn_primary:not(.weui-btn_disabled):active {
            transform: translateY(2px);
            box-shadow: 0 2px 5px rgba(7, 193, 96, 0.3);
        }
        
        .weui-btn_disabled {
            background: #E6E6E6;
            color: #999;
            box-shadow: none;
        }
        
        /* 大图预览模态框 */
        .modal {
            display: none;
            position: fixed;
            z-index: 100;
            left: 0;
            top: 0;
            width: 100%;
            height: 100%;
            background-color: rgba(0,0,0,0.9);
            overflow: auto;
            touch-action: manipulation;
        }
        
        .modal-content {
            display: flex;
            justify-content: center;
            align-items: center;
            height: 100%;
            padding: 20px;
        }
        
        .modal-img {
            max-width: 100%;
            max-height: 90vh;
            object-fit: contain;
            -webkit-user-select: none;
            user-select: none;
        }
        
        .close {
            position: absolute;
            top: 15px;
            right: 35px;
            color: #f1f1f1;
            font-size: 40px;
            font-weight: bold;
            cursor: pointer;
        }
        
        /* 编辑模式样式 */
        .edit-mode-badge {
            background: linear-gradient(to right, #FFA500, #FF8C00);
            color: white;
            padding: 4px 12px;
            border-radius: 20px;
            font-size: 14px;
            font-weight: 500;
            margin-left: 10px;
        }
        
        /* 动画效果 */
        @keyframes fadeIn {
            from { opacity: 0; }
            to { opacity: 1; }
        }
        
        @keyframes shake {
            0%, 100% { transform: translateX(0); }
            15%, 45%, 75% { transform: translateX(-5px); }
            30%, 60%, 90% { transform: translateX(5px); }
        }
        
        .shake {
            animation: shake 0.6s;
        }
        
        /* 响应式调整 */
        @media (max-width: 375px) {
            .weui-label {
                width: 70px;
            }
            
            .weui-cells__tips {
                padding-left: 70px;
            }
            
            .header-title {
                font-size: 22px;
            }
            
            .preview-item {
                width: calc(50% - 10px);
            }
            
            .close {
                right: 20px;
                font-size: 35px;
            }
        }
    </style>
</head>
<body>
    <div class="page-container">
         <!-- <div id="loading">授权检查中...</div> -->
        <div class="header">
            <h1 class="header-title">车辆起点登记🚚</h1>
        </div>
        
        <div class="weui-form">
            <div class="weui-cells__group weui-cells__group_form">
                <!-- 公司名称输入 -->
                <div class="weui-cells weui-cells_form">
                    <div class="weui-cell weui-cell_active">
                        <div class="weui-cell__hd">
                            <label class="weui-label">公司名称</label>
                        </div>
                        <div class="weui-cell__bd">
                            <input class="weui-input" id="company" type="text" placeholder="请输入公司名称" required>
                        </div>
                    </div>
                </div>
                <div class="weui-cells__tips" id="companyError">请输入公司名称</div>
                
                <!-- 货物重量输入 -->
                <div class="weui-cells weui-cells_form">
                    <div class="weui-cell weui-cell_active">
                        <div class="weui-cell__hd">
                            <label class="weui-label">货物重量</label>
                        </div>
                        <div class="weui-cell__bd">
                            <div class="weight-group">
                                <input class="weui-input" id="emptyWeight" type="text" placeholder="请输入重量" pattern="^\d+(\.\d{1,2})?$" required>kg
                            </div>
                        </div>
                    </div>
                </div>
                <div class="weui-cells__tips" id="weightError">请输入有效的重量值（整数或保留两位小数）</div>
                
                <!-- 货物照片上传 -->
                <div class="weui-cells weui-cells_form">
                    <div class="weui-cell weui-cell_active">
                        <div class="weui-cell__hd">
                            <label class="weui-label">货物照片</label>
                        </div>
                        <div class="weui-cell__bd">
                            <input class="weui-input" id="cargoPhotos" type="file" accept="image/*" multiple style="display: none;">
                            <button type="button" class="weui-btn weui-btn_default" id="uploadBtn">选择照片</button>
                            <div class="preview-container" id="cargoPreviews">
                                <div class="preview-placeholder">请上传货物照片</div>
                            </div>
                        </div>
                    </div>
                </div>
                <!-- 移除了照片错误提示 -->
            </div>
            
            <div class="weui-form__opr-area">
                <button type="button" class="weui-btn weui-btn_primary" id="submitBtn">提交登记</button>
            </div>
        </div>
    </div>

    <!-- 大图预览模态框 -->
    <div id="imageModal" class="modal">
        <span class="close">&times;</span>
        <div class="modal-content">
            <img id="modalImage" class="modal-img">
        </div>
    </div>

    <!-- 引入WeUI JS -->
    <script src="./weui/weui.min.js"></script>
    <script src="./weui/axios.min.js"></script>
    <script src="./axios.js"></script>
   <script src="./wechat-auth.js"></script>
    <script src="./api.js"></script>
    <script>
        // 获取DOM元素
        const companyInput = document.getElementById('company');
        const emptyWeightInput = document.getElementById('emptyWeight');
        const cargoPhotosInput = document.getElementById('cargoPhotos');
        const uploadBtn = document.getElementById('uploadBtn');
        const submitBtn = document.getElementById('submitBtn');
        const previewContainer = document.getElementById('cargoPreviews');
        const headerTitle = document.querySelector('.header-title');
        
        // 在其他界面使用
        const baseURL = request.instance.defaults.baseURL;
        
        // 验证状态
        let isCompanyValid = false;
        let isWeightValid = false;
        // 移除了照片验证状态
        
        // 存储当前预览的图片数据
        let currentPreviews = [];
        
        // 存储订单ID和编辑状态
        let currentOrderId = null;
        let isEditMode = false;
        
        // 从URL获取order_id参数
        function getOrderIdFromURL() {
            const urlParams = new URLSearchParams(window.location.search);
            return urlParams.get('order_id');
        }
        
        // 加载订单详情数据
        async function loadOrderDetail() {
            const orderId = getOrderIdFromURL();
            if (!orderId) return;
            
            currentOrderId = orderId;
            isEditMode = true;
            
            // 更新标题显示编辑模式
            headerTitle.innerHTML = '修改起点信息 <span class="edit-mode-badge">编辑模式</span>';
            
            const loading = weui.loading('加载订单详情中...');
            
            try {
                const response = await getOrderDetail({ order_id: orderId,openid:localStorage.getItem('wechat_openid') });
                const orderDetail = response.data || response;
                
                if (orderDetail && orderDetail) {
                    // 回显数据到表单
                    fillFormData(orderDetail);
                }
                
                loading.hide();
            } catch (error) {
                loading.hide();
                console.error('加载订单详情失败:', error);
                weui.toast('加载订单详情失败', {
                    className: 'weui-toast_warn',
                    duration: 2000
                });
            }
        }
        
        // 填充表单数据
 // 填充表单数据
function fillFormData(pidData) {
    // 回显公司名称
    if (pidData.company) {
        companyInput.value = pidData.company;
        isCompanyValid = true;
    }
    
    // 回显货物重量
    if (pidData.heavy) {
        // 确保重量显示为正确的格式
        const weightValue = parseFloat(pidData.heavy);
        if (!isNaN(weightValue)) {
            emptyWeightInput.value = weightValue.toFixed(2).replace(/\.?0+$/, '');
            isWeightValid = true;
        }
    }
    
    // 清空当前预览
    currentPreviews = [];
    previewContainer.innerHTML = '';
    
    // 处理图片数据
    if (pidData.images_url) {
        let copyUrls = [];
        
        // 处理copyUrl格式
        if (typeof pidData.images_url === 'string') {
            // 如果是逗号分隔的字符串
            copyUrls = pidData.images_url.split(',').filter(url => url.trim());
        } else if (Array.isArray(pidData.images_url)) {
            // 如果是数组
            copyUrls = pidData.images_url;
        }
        
        // 同时处理完整URL（用于显示）
        let fullImageUrls = [];
        if (pidData.images) {
            if (typeof pidData.images === 'string') {
                fullImageUrls = pidData.images.split(',').filter(url => url.trim());
            } else if (Array.isArray(pidData.images)) {
                fullImageUrls = pidData.images;
            }
        }
        
        if (copyUrls.length > 0) {
            // 添加图片到预览
            copyUrls.forEach((copyUrl, index) => {
                // 获取对应的完整URL，如果没有则使用copyUrl
                const fullUrl = fullImageUrls[index] || copyUrl;
                
                currentPreviews.push({
                    src: fullUrl, // 用于显示的完整URL
                    name: `已上传图片${index + 1}`,
                    file: null, // 编辑模式下没有原始File对象
                    index: currentPreviews.length,
                    uploadedUrl: copyUrl // 存储不带baseURL的地址，用于提交
                });
            });
            
            // 更新预览显示
            updatePreviews();
        }
    }
    
    // 如果没有copyUrl但有images，也处理
    else if (pidData.images) {
        let imageUrls = [];
        
        // 处理图片URL格式
        if (typeof pidData.images === 'string') {
            imageUrls = pidData.images.split(',').filter(url => url.trim());
        } else if (Array.isArray(pidData.images)) {
            imageUrls = pidData.images;
        }
        
        if (imageUrls.length > 0) {
            // 添加图片到预览
            imageUrls.forEach((imageUrl, index) => {
                // 从完整URL中提取不带baseURL的部分
                let copyUrl = imageUrl;
                if (imageUrl.includes(baseURL)) {
                    copyUrl = imageUrl.replace(baseURL, '');
                }
                
                currentPreviews.push({
                    src: imageUrl, // 完整URL用于显示
                    name: `已上传图片${index + 1}`,
                    file: null, // 编辑模式下没有原始File对象
                    index: currentPreviews.length,
                    uploadedUrl: copyUrl // 不带baseURL的地址，用于提交
                });
            });
            
            // 更新预览显示
            updatePreviews();
        }
    }
    
    // 更新提交按钮状态
    // updateSubmitButton();
}
        
        // 初始化隐藏所有错误提示
        document.querySelectorAll('.weui-cells__tips').forEach(el => el.style.display = 'none');
        
        // 公司名称验证
        function validateCompany(company) {
            return company.trim().length >= 2 && company.trim().length <= 50;
        }
        
        // 重量验证 - 支持整数或保留两位小数
        function validateWeight(weight) {
            // 正则表达式：匹配整数或最多两位小数的数字
            const weightRegex = /^\d+(\.\d{1,2})?$/;
            
            if (!weightRegex.test(weight)) {
                return false;
            }
            
            const weightValue = parseFloat(weight);
            return !isNaN(weightValue) && weightValue > 0;
        }
        
        // 格式化重量输入
        function formatWeightInput(value) {
            // 移除非数字字符，除了小数点
            let cleaned = value.replace(/[^\d.]/g, '');
            
            // 确保只有一个小数点
            const parts = cleaned.split('.');
            if (parts.length > 2) {
                cleaned = parts[0] + '.' + parts.slice(1).join('');
            }
            
            // 限制小数点后最多两位
            if (parts.length === 2) {
                cleaned = parts[0] + '.' + parts[1].slice(0, 2);
            }
            
            return cleaned;
        }
        
        // 照片验证 - 已移除
        
        // 更新提交按钮状态
        function updateSubmitButton() {
            // submitBtn.disabled = !(isCompanyValid && isWeightValid);
            
            // // 如果是编辑模式，更新按钮文本
            // if (isEditMode) {
            //     submitBtn.textContent = '更新信息';
            // }
        }
        
        // 公司名称输入验证
        companyInput.addEventListener('input', function() {
            const company = this.value.trim();
            isCompanyValid = validateCompany(company);
            const companyError = document.getElementById('companyError');
            
            if (company.length > 0) {
                if (isCompanyValid) {
                    companyError.style.display = 'none';
                } else {
                    companyError.style.display = 'block';
                }
            } else {
                companyError.style.display = 'none';
            }
            
            updateSubmitButton();
        });
        
        // 重量输入验证
        function validateWeightInputs() {
            const weightValue = emptyWeightInput.value.trim();
            isWeightValid = validateWeight(weightValue);
            const weightError = document.getElementById('weightError');
            
            if (weightValue.length > 0) {
                if (isWeightValid) {
                    weightError.style.display = 'none';
                } else {
                    weightError.style.display = 'block';
                }
            } else {
                weightError.style.display = 'none';
            }
            
            updateSubmitButton();
        }
        
        // 重量输入格式化
        emptyWeightInput.addEventListener('input', function() {
            // 格式化输入
            this.value = formatWeightInput(this.value);
            
            // 验证输入
            validateWeightInputs();
        });
        
        // 重量输入失去焦点时进一步格式化
        emptyWeightInput.addEventListener('blur', function() {
            const value = this.value.trim();
            if (value && validateWeight(value)) {
                const weightValue = parseFloat(value);
                // 确保显示两位小数，但如果是整数则不显示小数部分
                this.value = weightValue % 1 === 0 ? weightValue.toString() : weightValue.toFixed(2);
            }
        });
        
        // 照片上传按钮点击
        uploadBtn.addEventListener('click', function() {
            cargoPhotosInput.click();
        });
        
        // 照片上传处理 - 支持追加上传
        cargoPhotosInput.addEventListener('change', function(e) {
            const files = Array.from(e.target.files);
            
            if (files.length === 0) return;
            
            // 移除之前的占位符
            if (previewContainer.querySelector('.preview-placeholder')) {
                previewContainer.innerHTML = '';
            }
            
            // 处理每张图片
            files.forEach((file, index) => {
                if (!file.type.match('image.*')) return;
                
                const reader = new FileReader();
                reader.onload = function(e) {
                    // 添加到当前预览数组
                    currentPreviews.push({
                        src: e.target.result,
                        name: file.name,
                        file: file, // 保存原始File对象
                        index: currentPreviews.length,
                        uploadedUrl: null // 用于存储上传后的URL
                    });
                    
                    // 更新预览显示
                    updatePreviews();
                    
                    // 移除了照片验证状态更新
                    updateSubmitButton();
                };
                reader.onerror = function() {
                    console.error('图片加载失败');
                };
                reader.readAsDataURL(file);
            });
            
            // 清空input以便再次选择相同文件
            cargoPhotosInput.value = '';
        });
        
        // 更新预览显示
        function updatePreviews() {
            previewContainer.innerHTML = '';
            
            if (currentPreviews.length === 0) {
                previewContainer.innerHTML = '<div class="preview-placeholder">请上传货物照片</div>';
                // 移除了照片验证状态更新
                updateSubmitButton();
                return;
            }
            
            currentPreviews.forEach((preview, index) => {
                const previewItem = document.createElement('div');
                previewItem.className = 'preview-item';
                previewItem.innerHTML = `
                    <button class="remove-btn" data-index="${index}">×</button>
                    <img src="${preview.src}" alt="预览">
                    <div class="preview-info">${preview.name}</div>
                `;
                previewContainer.appendChild(previewItem);
                
                // 添加点击放大事件
                previewItem.querySelector('img').onclick = function() {
                    showLargePreview(preview.src);
                };
                
                // 添加删除按钮事件
                previewItem.querySelector('.remove-btn').onclick = function() {
                    removeImage(this.dataset.index);
                };
            });
        }
        
     // 移除图片
        function removeImage(index) {
            // 从预览数组中移除 - 正确用法：删除指定索引的一个元素
            currentPreviews.splice(index, 1);
            
            // 更新剩余图片的索引
            currentPreviews.forEach((preview, i) => {
                preview.index = i;
            });
            
            // 更新预览显示
            updatePreviews();
        }
        
        // 显示大图预览
        function showLargePreview(imageSrc) {
            const modal = document.getElementById('imageModal');
            const modalImg = document.getElementById('modalImage');
            
            modal.style.display = "block";
            modalImg.src = imageSrc;
            
            // 禁用滚动
            document.body.style.overflow = 'hidden';
        }
        
        // 关闭大图预览
        document.querySelector('.close').onclick = function() {
            document.getElementById('imageModal').style.display = "none";
            document.body.style.overflow = 'auto';
        };
        
        // 点击模态框背景关闭
        document.getElementById('imageModal').onclick = function(event) {
            if (event.target === this) {
                this.style.display = "none";
                document.body.style.overflow = 'auto';
            }
        };
        
        // 上传单张图片到服务器
        async function uploadSingleImage(file) {
            const formData = new FormData();
            formData.append('file', file);
            
            try {
                // 调用上传接口
                const response = await axios.post(baseURL+'/common/upload', formData, {
                    headers: {
                        'Content-Type': 'multipart/form-data'
                    }
                });
                
                if (response.data && response.data.code === 200) {
                    return response.data.data; // 返回上传后的URL
                } else {
                    throw new Error(response.data?.message || '上传失败');
                }
            } catch (error) {
                console.error('图片上传失败:', error);
                throw error;
            }
        }
        
        // 批量上传所有图片
      // 批量上传所有图片
        async function uploadAllImages() {
            const uploadedUrls = [];
            
            for (let i = 0; i < currentPreviews.length; i++) {
                const preview = currentPreviews[i];
                
                // 如果图片已经有上传的URL（编辑模式下），直接使用
                if (preview.uploadedUrl && !preview.file) {
                    uploadedUrls.push(preview.uploadedUrl);
                    continue;
                }
                
                // 否则上传新图片
                try {
                    const uploadedUrl = await uploadSingleImage(preview.file);
                    // 只存储不带baseURL的部分
                    let copyUrl = uploadedUrl.url;
                    if (uploadedUrl.url.includes(baseURL)) {
                        copyUrl = uploadedUrl.url.replace(baseURL, '');
                    }
                    uploadedUrls.push(copyUrl);
                    
                    // 更新预览项的上传状态
                    preview.uploadedUrl = copyUrl;
                    preview.src = uploadedUrl.url; // 更新显示用的完整URL
                    
                    console.log(`图片 ${i + 1}/${currentPreviews.length} 上传成功:`, copyUrl);
                } catch (error) {
                    console.error(`图片 ${preview.name} 上传失败:`, error);
                    throw new Error(`图片 ${preview.name} 上传失败`);
                }
            }
            
            return uploadedUrls;
        }
        
        // 提交按钮点击事件
        submitBtn.addEventListener('click', async function() {
            // 最终验证
            
            
            const company = companyInput.value.trim();
            const emptyWeight = emptyWeightInput.value.trim();
            
            // 重置所有错误提示和抖动效果
            document.querySelectorAll('.weui-cells__tips').forEach(el => el.style.display = 'none');
            document.querySelectorAll('.shake').forEach(el => el.classList.remove('shake'));
    
            // 强制验证所有字段
            isCompanyValid = company.length > 0 && validateCompany(company);
            isWeightValid = emptyWeight.length > 0 && validateWeight(emptyWeight);
            // 移除了照片验证
            
            // 检查并显示未填写的字段错误
            let hasError = false;
            
            if (!company) {
                document.getElementById('companyError').textContent = "请输入公司名称";
                document.getElementById('companyError').style.display = 'block';
                companyInput.parentElement.parentElement.classList.add('shake');
                hasError = true;
            } else if (!isCompanyValid) {
                document.getElementById('companyError').textContent = "公司名称长度应在2-50个字符之间";
                document.getElementById('companyError').style.display = 'block';
                companyInput.parentElement.parentElement.classList.add('shake');
                hasError = true;
            }
            
            if (!emptyWeight) {
                document.getElementById('weightError').textContent = "请输入货物重量";
                document.getElementById('weightError').style.display = 'block';
                emptyWeightInput.parentElement.parentElement.classList.add('shake');
                hasError = true;
            } else if (!isWeightValid) {
                document.getElementById('weightError').textContent = "请输入有效的重量值（整数或保留两位小数）";
                document.getElementById('weightError').style.display = 'block';
                emptyWeightInput.parentElement.parentElement.classList.add('shake');
                hasError = true;
            }
            
            // 移除了照片验证
            
            // 如果有错误，显示提示并返回
            if (hasError) {
                // 移除抖动效果
                setTimeout(() => {
                    document.querySelectorAll('.shake').forEach(el => {
                        el.classList.remove('shake');
                    });
                }, 600);
                
                // 滚动到第一个错误的位置
                const firstErrorElement = document.querySelector('.weui-cells__tips[style="display: block;"]');
                if (firstErrorElement) {
                    firstErrorElement.scrollIntoView({ behavior: 'smooth', block: 'center' });
                }
                
                return;
            }
            
            // 显示加载中
            const loading = weui.loading('提交中...');
            
            try {
                // 第一步：上传所有图片（如果有的话）
                let imageUrls = [];
                
                if (currentPreviews.length > 0) {
                    const imageUploadLoading = weui.loading('上传图片中...');
                    try {
                        imageUrls = await uploadAllImages();
                        imageUploadLoading.hide();
                    } catch (uploadError) {
                        imageUploadLoading.hide();
                        loading.hide();
                        weui.toast('图片上传失败，请重试', {
                            className: 'weui-toast_warn',
                            duration: 2000
                        });
                        return;
                    }
                }
                
                console.log(imageUrls,'imageUrls');
                
                // 第二步：准备提交数据
                const submitData = {
                    company: company,
                    heavy: emptyWeight,
                    openid: localStorage.getItem('wechat_openid'),
                   images: imageUrls.join(',') // 这里存储的是不带baseURL的地址
                };
                
                // 如果是编辑模式，添加订单ID
                if (isEditMode && currentOrderId) {
                    submitData.order_id = currentOrderId;
                }
                
                console.log('提交数据:', submitData);
               
                // 第三步：调用API提交数据
                let response;
                if(isEditMode&& currentOrderId){
             response = await orderEdit(submitData);
                }else{
                          response = await startLogin(submitData);
                }
           
                
                loading.hide();
                
                if (response.code === 200) {
                    // 显示成功提示
                    weui.toast(isEditMode ? '更新成功' : '登记成功', {
                        className: 'weui-toast_success',
                        duration: 2000
                    });

                    if(isEditMode){
                          setTimeout(() => {
                       window.location.href='detail.html';
                    }, 2000);
                    }else{

                    // 3秒后返回上一页
                    setTimeout(() => {
                       window.location.href='orderList.html';
                    }, 2000);
                     }
                } else {
                    throw new Error(response.message || '提交失败');
                }
                
            } catch (error) {
                loading.hide();
                console.error('提交失败:', error);
                
                weui.toast('提交失败，请重试', {
                    className: 'weui-toast_warn',
                    duration: 2000
                });
            }
        });
        
        // 重置表单
        function resetForm() {
            companyInput.value = '';
            emptyWeightInput.value = '';
            currentPreviews = [];
            previewContainer.innerHTML = '<div class="preview-placeholder">请上传货物照片</div>';
            isCompanyValid = isWeightValid = false;
            updateSubmitButton();
            document.querySelectorAll('.weui-cells__tips').forEach(el => el.style.display = 'none');
        }
        
        // 初始化
        function init() {
            // 初始化按钮状态
            updateSubmitButton();
            
            // 检查是否有order_id参数，如果有则加载订单详情
            const orderId = getOrderIdFromURL();
            if (orderId) {
                loadOrderDetail();
            }
        }
        
        // 页面加载完成后执行初始化
        document.addEventListener('DOMContentLoaded',async function() {
                 try {
                // 检查授权
                // const isAuthed = await weChatAuth.checkAuth();
                
                // if (isAuthed) {
                   init()
                // } else {
                    // 授权中，等待跳转
                    // document.getElementById('loading').innerHTML = '微信授权中...';
                // }
            } catch (error) {
                console.error('页面初始化失败:', error);
                // document.getElementById('loading').innerHTML = '加载失败，请刷新页面';
            }
         
        } );
    </script>
</body>
</html>